var tableIns;
var $;
layui.use(['jquery', 'element', 'table', 'form', 'layer','upload'], function () {
    var element = layui.element;
    $ = layui.jquery;
    var form = layui.form;
    var table = layui.table;
    var layer = layui.layer;
    var upload = layui.upload;
    var createId = localStorage.getItem('createId');

    $("#buttons1").removeClass("layui-btn-primary");
    $("#buttons1").click(function () {
        $(".buttons").addClass("layui-btn-primary")
        $("#buttons1").removeClass("layui-btn-primary");
    })
    $("#buttons2").click(function () {
        $(".buttons").addClass("layui-btn-primary")
        $("#buttons2").removeClass("layui-btn-primary");
    })
    $("#buttons3").click(function () {
        $(".buttons").addClass("layui-btn-primary")
        $("#buttons3").removeClass("layui-btn-primary");
    })
    $("#buttons4").click(function () {
        $(".buttons").addClass("layui-btn-primary")
        $("#buttons4").removeClass("layui-btn-primary");
    })
    $("#buttons5").click(function () {
        $(".buttons").addClass("layui-btn-primary")
        $("#buttons5").removeClass("layui-btn-primary");
    })

    $('input[name=createId]').val(createId);
    $('input[name=updateId]').val(createId);
    var settingss = {
        view: {
            dblClickExpand: false
        },
        /*edit: {
            enable: true,
            editNameSelectAll: true,
            removeTitle: '删除',
            renameTitle: '重命名',

        },*/
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "categroyId",   //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                enable: true,
                name: "title"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check: {
            enable: false,
            nocheckInherit: true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback: {
            onRightClick: onRightClick,
            // beforeRemove: beforeRemove,//点击删除时触发，用来提示用户是否确定删除（可以根据返回值 true|false 确定是否可以删除）
            // beforeEditName: beforeEditName,//点击编辑时触发，用来判断该节点是否能编辑
            beforeRename: beforeRename,//编辑结束时触发，用来验证输入的数据是否符合要求(也是根据返回值 true|false 确定是否可以编辑完成)
            // beforeDrag: beforeDrag,//用户禁止拖动节点
            onClick: chooseNode,
        }
    };

    //鼠标右键功能
    function onRightClick(event, treeId, treeNode) {
        /* if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
             zTree.cancelSelectedNode();
             showRMenu("root", event.clientX, event.clientY);
         } else */
        if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            showRMenu("node", event.clientX, event.clientY);
        }
    }

    //修改前判断
    function beforeRename(treeId, treeNode, newName) {
        if (newName.length == 0) {
            layer.msg("节点名称不能为空.");
            var zTree = $.fn.zTree.getZTreeObj("ztree");
            setTimeout(function () {
                zTree.editName(treeNode)
            }, 10);
            return false;
        }
        return true;
    }

    function showRMenu(type, x, y) {
        $("#rMenu ul").show();
        if (type == "root") {
            $("#m_del").hide();
        } else {
            $("#m_del").show();
        }

        y += document.body.scrollTop;
        x += document.body.scrollLeft;
        rMenu.css({"top": y + "px", "left": x + "px", "visibility": "visible"});

        $("body").bind("mousedown", onBodyMouseDown);
    }

    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            rMenu.css({"visibility": "hidden"});
        }
    }

    //添加节点
    addTreeNode = function addTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var parentId = nodes[0].categroyId;
        layer.open({
            maxmin: true,
            type: 1,
            title: "添加节点",
            area: ['400px', '250px'],
            shade: 0.4,
            offset: ['250px', '650px'],
            content: "<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>" +
                "<label class='layui-input-label'>添加分类：</label>"
                + "<input type='text' name='title' style='width:220px;height:30px;'id='addNode' lay-verify='required' placeholder='课程分类'>"
                + "</div></form>",
            btn: ['添加', '取消'],
            yes: function () {
                var title = $("#addNode").val();
                var createId = $('input[name=createId]').val();
                var jsCourseCategroy = {
                    'parentId': parentId,
                    'title': title,
                    'createId': createId,
                    'categroy': 1,
                }
                $.ajax({
                    url: '/courseTree/addCourseClass',
                    dataType: 'json',
                    data: jsCourseCategroy,
                    success: function (data) {
                        if (data.data) {
                            layer.msg("添加成功");
                            location.reload();
                        } else {
                            layer.msg("添加失败");
                        }
                    }
                });
            }
        })
    }
    //删除节点
    removeTreeNode = function removeTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var categroyId = nodes[0].categroyId;
        if (confirm("确认删除" + nodes[0].title + "课程类?")) {
            if (nodes[0].isParent) {
                layer.msg("不能删除该目录，请从最底层目录开始删除!");
                return false;
            }
            $.ajax({
                url: '/courseTree/delCourseClass',
                data: {"categroyId": categroyId},
                dataType: 'json',
                success: function (data) {
                    if (data.data) {
                        layer.msg("删除成功");
                        location.reload();
                        return true;
                    } else {
                        layer.msg("删除失败");
                        return false;
                    }
                }
            });
        }
        return false;
    }
    //修改节点
    edit = function edit() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var categroyId = nodes[0].categroyId;
        layer.open({
            type: 1,
            title: '修改节点',
            area: ['400px', '250px'],
            shade: 0,
            offset: 'auto',
            maxmin: true,
            content:"<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>"+
                "<label class='layui-input-label'>修改分类：</label>"
                +"<input type='text' name='title' style='width:220px;height:30px;'id='updateNode' lay-verify='required' placeholder='课程分类'>"
                +"</div></form>",
            btn : ['确定', '取消'],
            yes: function () {
                var newName = $("#updateNode").val();
                var updateId = $('input[name=updateId]').val();
                var jsProductCategroy = {
                    'categroyId': categroyId,
                    'title': newName,
                    'updateId': updateId
                }
                if (newName.length != 0) {
                    $.ajax({
                        url: '/courseTree/updateCourseClass',
                        data: jsProductCategroy,
                        dataType: 'json',
                        success: function (data) {
                            if (data.data) {
                                layer.msg("修改成功");
                                document.location.reload();
                                return true;
                            } else {
                                layer.msg("修改失败");
                                return false;
                            }
                        }
                    });
                } else {
                    layer.msg("不能为空");
                }
            }
        });
    }

    //点击节点，展示对应类别下课程信息
    function chooseNode(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        var nodes = zTree.getSelectedNodes();
        var jsCourse = {
            'categroyId': treeNode.categroyId,
            'result': '1'
        }
        getTable(jsCourse);
    }

    //加载树
    var zTree, rMenu;
    $(document).ready(function () {
        $.ajax({
            url: "/courseTree/getTree",
            type: 'post',
            dataType: 'json',
            success: function (data) {
                zTree = $.fn.zTree.init($("#ztree"), settingss, data.data); //初始化树
                zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            }
        })
        rMenu = $("#rMenu");
    });

    var jsProduct = {
    }
    //初始调用的表
    getTable(jsProduct);

    getCourseClass();
    function getCourseClass() {
        $.ajax({
            url: '/courseTable/getCourseClass',
            type: 'post',
            dataType: 'json',
            success: function (data) {
                var opt="<select name='classId' id='classId'>";
                opt+="<option value=''>请选择课程分类</option>";
                for(var da in data.data) {
                    var ba=da;
                    da++;
                    opt +="<option value='"+da+ "'>"+data.data[ba].title+"</option>"
                }
                opt+="</select>"
                $("#sot").html(opt);
                //刷新下拉框
                form.render('select');
            }
        });
    }
    //getTable方法
    function getTable(jsProduct) {
        var userId=null;
        $.ajax({
            url: "/login/getUser",
            type: "post",
            dataType: "json",
            success: function (user) {
                console.log(user.data.userId);
                userId=user.data.userId;
                console.log(userId);
                jsProduct.updateId=userId;
                $.ajax({
                    url: '/courseTable/getTable',
                    type: 'post',
                    dataType: 'json',
                    data: jsProduct,
                    success: function (data) {
                        tablereload(data.data);
                    }
                });
            },
        })
    }

    function tablereload(date) {
        table.render({
            elem: '#table',
            data: date,
            title: '数据列表',
            limit: 10,
            id: 'table',
            toolbar: '#toptool',
            page: {
                layout: ['count', 'prev', 'page', 'next', 'skip', 'refresh'],
                first: "首页",
                last: "尾页",
            },
            size: 'lg',
            cols: [[//定义列
                {type: 'checkbox'},//复选框靠左
                {field: 'courseId', title: '课程编号', align: 'center'},
                {
                    field: "url", title: "课程图片", align: 'center', templet: function (data) {
                        return "<img src='" + data.url + "'/>";
                    }
                },
                {field: 'coursePrimary', title: "课程名称", align: 'center'},
                {
                    field: 'courseNprice',
                    title: "课程价格",
                    align: 'center',
                    templet: function (data) {
                        return "￥" + data.courseNprice;
                    }
                },
                {
                    field: 'courseStatus',
                    title: "上架/下架",
                    align: 'center',
                    templet: function (data) {
                        if(data.courseStatus==2){
                            var radio = '<a href="javascript:updateStatus('+data.courseId+","+data.courseStatus+');"><input class="layui-input swi" type="checkbox" name="sate" lay-skin="switch" lay-text="上架|下架" lay-filter="switchTest" value="'+data.courseStatus+'" checked></a>'
                        }else{
                            var radio = '<a href="javascript:updateStatus('+data.courseId+','+data.courseStatus+');"><input class="layui-input swi" type="checkbox" name="sate" lay-skin="switch" lay-text="上架|下架" lay-filter="switchTest" value="'+data.courseStatus+'"></a>'
                        }
                        return radio;
                    }
                },
                {field: 'title', title: "课程分类", align: 'center'},
                {field: 'remarks', title: "审核状态", align: 'center',
                    templet: function (data) {
                        if(data.courseCstatus==4){
                            var radio = '<p>审核通过</p><a href="javascript:courseCstatus('+data.courseId+","+data.courseCstatus+');" style="color: #0EAA9E">审核详细</a>'
                        }else if(data.courseCstatus==3){
                            var radio = '<p>未审核</p><a href="javascript:courseCstatus('+data.courseId+","+data.courseCstatus+');" style="color: #0EAA9E">审核详细</a>'
                        }else if(data.courseCstatus==5){
                            var radio = '<p>待审核</p><a href="javascript:courseCstatus('+data.courseId+","+data.courseCstatus+');" style="color: #0EAA9E">审核详细</a>'
                        }else if(data.courseCstatus==6){
                            var radio = '<p>审核失败</p><a href="javascript:courseCstatus('+data.courseId+","+data.courseCstatus+');" style="color: #0EAA9E">审核详细</a>'
                        }else{
                            var radio = '<p>未知</p>'
                        }
                        return radio;
                    }
                },
                {
                    field: '', title: "操作", align: 'center', templet: function (data) {
                        return "<div>" +
                            "<a href='javascript:getProduct(" + data.courseId + ");' style='color: #0EAA9E;margin-right: 10px'>查看</a>" +
                            "<a href='javascript:updateCourse(" + data.courseId + ");' style='color: #0EAA9E'>编辑</a><br/>" +
                            "<a href='javascript:getCoursejournal(" + data.courseId + ");' style='color: #0EAA9E; margin-right: 10px'>日志</a>" +
                            "<a href='javascript:delCourse(" + data.courseId + ");' style='color: #0EAA9E'>删除</a>" +
                            "</div>";
                    }
                },
            ]],
        });
    }
    gCha = function gCha(){
        var course = {
        }
        $.ajax({
            url: '/courseTable/getTable',
            type: 'post',
            dataType: 'json',
            data: course,
            success: function (data) {
                tablereload(data.data);
            }
        });
    }

    shangJia = function shangJia(){
        var courseStatus=2;
        var param={
            "courseStatus":courseStatus
        }
        getTable(param);
    }

    weiJia = function weiJia() {
        var courseStatus = 3;
        var param={
            "courseStatus":courseStatus
        }
        getTable(param);
    }

    dShen = function dShen() {
        var remarks=5;
        var param={
            "remarks":remarks
        }
        getTable(param);
    }

    Bhui = function Bhui(){
        var remarks=6;
        var param={
            "remarks":remarks
        }
        getTable(param);
    }

    //搜索
    search = function search() {
        var productName = $('input[name=productName]').val();
        var courseNprice = $('input[name=courseNprice]').val();

        var classification = document.getElementById("classId");
        var indexClass = classification.selectedIndex;
        var classId = classification.options[indexClass].value;

        // var state = document.getElementById("productSate");
        // var indexState = state.selectedIndex;
        // var productSate = state.options[indexState].value;
        var productLabel = $('input[name=productLabel]').val();
        var param = {
            'coursePrimary':productName,
            'classId':classId,
            "courseNprice":courseNprice,
            'courseCstatus':'4'
            //'productSate':productSate
        }
        getTable(param);
    }
    //删除课程
    delCourse = function delCourse(id) {
        layer.confirm('是否确定删除此条数据', {
                icon: 3, title: '提示'
            },function(){
                var userId=localStorage.getItem("createId");
                $.ajax({
                    url: '/courseTable/delCourse',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        'id': id,
                        'userId':userId
                    },
                    success: function (data) {
                        if (data.data!=null) {
                            alert("删除成功");
                            location.reload();
                        } else {
                            alert("删除失败");
                            location.reload();
                        }
                    }
                });
            }
        )
    }
    //查看当前课程的日志
    getCoursejournal = function getCoursejournal(courseId){
        $.ajax({
            url: "/courseTable/getCoursejournal",
            type: "post",
            dataType: "json",
            data: {"courseId": courseId},
            success: function (data) {
                localStorage.setItem("journalId",courseId);
                layer.open({
                    type: 2,
                    title: "课程日志",
                    area: ['1200px', '700px'],
                    shade: 0,
                    offset: 't',
                    maxmin: true,
                    content: "/course/course-journal.html",
                    success: function (layero, index) {

                    }
                });
            },
        })
    }

    //查看课程详情
    getProduct = function getProduct(courseId) {
        var userId=localStorage.getItem("createId");
        $.ajax({
            url: "/courseTable/getCourse",
            type: "post",
            dataType: "json",
            data: {
                "courseId": courseId,
                "updateId":userId
            },
            success: function (data) {
                devicesMsg(data);
            },
        })
    }

    function devicesMsg(data) {
        var userName="";
        var userAcc="";
        layer.open({
            type: 2,
            title: "课程详情",
            area: ['990px', '650px'],
            shade: 0,
            offset: 'auto',
            maxmin: true,
            btn:['关闭'],
            content: "/course/course-see.html",
            success: function (layero, index) {
                $.ajax({
                    url: "/login/getUser",
                    type: "post",
                    dataType: "json",
                    success: function (user) {
                        userName=user.data.trueName;
                        userAcc=user.data.account;
                        console.log(userName,userAcc);
                        var obj = layero.find('iframe').contents();
                        obj.find("#productCode").val(data.data.courseName);
                        obj.find("#productName").val(data.data.createDate);
                        obj.find("#currentpriceProduct").val(data.data.userName);
                        obj.find("#shoucang").val(data.data.collectNum);
                        obj.find("#xiaoliang").val(data.data.title);
                        obj.find("#title").val(data.data.courseNprice);
                        obj.find("#productSate").val(data.data.coursePrimary);
                        obj.find("#productLabel").val(data.data.likeNum);
                        obj.find("#hits").val(data.data.collectNum);
                        obj.find("#productDescription").val(data.data.courseIntro);
                        obj.find("#beizhu").val(data.data.courseInfo);
                        obj.find("#mainImage").attr('src',data.data.url);
                        obj.find("#Image").attr('src',data.data.courseUrl);
                        obj.find("#name").html('用户名：<input type="text"  value="'+userName+'">');
                        obj.find("#acc").html('账号：<input type="text"  value="'+userAcc+'">');
                    },
                })

            }
        });
    }

    /*表格详情结束*/
    //开关事件
    updateStatus = function updateStatus( id,courseStatus) {
        if(courseStatus==2){
            courseStatus=3;
        }else{
            courseStatus=2;
        }
        $.ajax({
            url: '/courseTable/updateCourseStatus',
            type: 'post',
            dataType: 'json',
            data: {
                'id': id,
                'courseStatus': courseStatus
            },
            success:function (data) {
                layer.msg("修改成功");
            }
        })
    }

    //查看当前课程的审核
    courseCstatus = function courseCstatus(courseId,courseCstatus){
        $.ajax({
            url: '/courseTable/getRecord',
            type: 'post',
            dataType: 'json',
            data: {
                'courseId': courseId
            },
            success: function (data) {
                localStorage.setItem("recId",courseId);
                layer.open({
                    type: 2,
                    title: "课程审核详情",
                    area: ['1200px', '700px'],
                    shade: 0,
                    offset: 't',
                    maxmin: true,
                    content: "/course/course-record.html",
                    success: function (layero, index) {

                    }
                });
            },
        })
    }


    //高级检索
    retrieval = function retrieval() {
        var flag=true;
        layer.open({
            type: 2,
            title: "高级检索",
            area: ['600px', '350px'],
            content: "/course/course-search-table.html",
            shade: 0,
            offset: 'auto',
            maxmin: true,
            cancel: function(index, layero){
                flag=false;
                layer.close(index)
                return false;
            },
            end: function (layero, index) {
                var jsCourse = $('input[name=jsProduct]').data('jsProduct');
                if(flag){
                    tablereload(jsCourse);
                }
            }
        })
    }


    /*表格修改*/
    updateCourse = function updateCourse(courseId) {
        $.ajax({
            url: "/courseTable/getCourse",
            type: "post",
            dataType: "json",
            data: {"courseId": courseId},
            success: function (data) {
                $.ajax({
                    url: "/login/getUser",
                    type: "post",
                    dataType: "json",
                    success: function (user) {
                        localStorage.setItem("courseId",courseId);
                        localStorage.setItem("classId",data.data.classId);
                        localStorage.setItem("classId",data.data.classId);
                        localStorage.setItem("classId",data.data.classId);
                        layer.open({
                            type: 2,
                            title: "修改",
                            area: ['1200px', '700px'],
                            shade: 0,
                            offset: 't',
                            maxmin: true,
                            content: "/course/course-update.html",
                            success: function (layero, index) {
                                userName=user.data.trueName;
                                userAcc=user.data.account;
                                console.log(userName,userAcc);
                                var obj = layero.find('iframe').contents();
                                localStorage.setItem("classId",data.data.classId);
                                localStorage.setItem("courseUrl",data.data.courseUrl);
                                localStorage.setItem("url",data.data.url);
                                localStorage.setItem("money",data.data.title);
                                localStorage.setItem("coursePrice",data.data.courseNprice);
                                localStorage.setItem("courseCstatus",data.data.courseCstatus);
                                localStorage.setItem("courseStatus",data.data.courseStatus);

                                obj.find("#test1").val(data.data.createDate);
                                obj.find("#productCode").val(data.data.courseName);
                                obj.find("#productName").val(data.data.createDate);
                                obj.find("#currentpriceProduct").val(data.data.userName);
                                obj.find("#shoucang").val(data.data.collectNum);
                                obj.find("#xiaoliang").val(data.data.title);
                                obj.find("#title").val(data.data.courseNprice);
                                obj.find("#productSate").val(data.data.coursePrimary);
                                obj.find("#productLabel").val(data.data.likeNum);
                                obj.find("#hits").val(data.data.collectNum);
                                obj.find("#productDescription").val(data.data.courseIntro);
                                obj.find("#beizhu").val(data.data.courseInfo);
                                obj.find("#mainImage").attr('src',data.data.url);
                                obj.find("#video").attr('src',data.data.courseUrl);
                                obj.find("#name").html('用户名：<input type="text"  value="'+userName+'">');
                                obj.find("#acc").html('账号：<input type="text"  value="'+userAcc+'">');
                            }
                        });
                    },
                })
            }
        });

    }
    /*表格修改结束*/

    //导入
    importTable = function importTable() {
        layer.open({
            type: 2,
            title: "上传文件",
            area: ['259px','205px'],
            shade: 0.4,
            maxmin:true,
            offset: "auto",
            content: "/goods/import-excel.html",
            cancel: function(){
                location.reload();
            }
        });

    }
});



//添加课程
function addProduct() {
    parent.$('#quickHref').val("添加课程");
    parent.getQuick();
    return;
}

//刷新
function Refresh() {
    location.reload();
}

//返回
function goBack() {
    parent.$('#beforeHref').val($('#courseTable').text());
    parent.before();
    return false;
}